// 接口配置
const baseUrl = process.env.VUE_APP_BASEURL || 'http://接口域名/'
const uploadPresignedUrl = '获取上传签名/get-upload-token'
const batchUploadPresignedUrl = '批量获取上传签名/get-batch-upload-token'

export default {
	/**上传文件*/
  upload(file) {
    let _this = this;
    return _this.getUploadKey(file)
      .then((keyInfo) => { // keyInfo:{resourceKey,name,signUrl}
        return _this.uploadFileByKey(file, keyInfo);
      })
      .catch((error) => {
        return Promise.reject(error);
      })
  },
  uploadFileByKey(file, keyInfo = {}) {
    return new Promise((resolve, reject) => {
      // 如果是 base64 字符串，转成 File 对象
      if (typeof file === 'string') {
        file = this.base64ToFile(file);
      }
			let formData = new FormData();
			formData.append('file', file)
			formData.append('key', keyInfo.key)
			formData.append('token', keyInfo.token)
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status == 200) {
					let data = {}
					try {data = JSON.parse(this.responseText)} catch (err) {}
          resolve(data);
        } else if (this.readyState === 4) {
          reject('文件上传失败！');
        }
      })
      xhr.open('POST', keyInfo.host);
      xhr.send(formData);
    })
  },
  // 从服务端获取上传签名信息-批量
  getBatchUploadKey(fileArr) {
    const reqUrl = baseUrl + batchUploadPresignedUrl;
    const fileNames = [];
    for (let i = 0; i < fileArr.length; i++) {
      fileNames.push(fileArr[i].name);
    }
    return new Promise((resolve, reject) => {
      let fileNamesStr = JSON.stringify(fileNames);
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status == 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取上传签名信息失败！');
        }
      });
      xhr.open('GET', `${reqUrl}?arr=${encodeURIComponent(fileNamesStr)}`);
      xhr.send();
    })
  },
  // 从服务端获取上传签名信息-单个
  getUploadKey(file) {
		let _this = this;
		return _this.getBatchUploadKey([file]);
  },
}
